package utils

import (
	"errors"
	"io/ioutil"
	"log"
	"os"
	"runtime"
	"sort"
	"strings"
)

type File struct {
	Name  string
	Path  string
	IsDir bool
}

type FileSlice []File

func (s FileSlice) Len() int {
	return len(s)
}

func (s FileSlice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s FileSlice) Less(i, j int) bool {
	return s[i].Name < s[j].Name
}

// dealPath 处理不同平台的分隔符
func DealPath(path string) string {
	if strings.Contains(runtime.GOOS, "window") {
		s := strings.Split(path, "/")
		return strings.Join(s, "\\")
	}
	s := strings.Split(path, "\\")
	return strings.Join(s, "/")
}

// GetFolders 获取指定目录下的所有文件夹
func GetFolders(path string) []File {
	folders := make([]File, 0)
	path = DealPath(path)
	f, err := ioutil.ReadDir(path)
	if err != nil {
		log.Fatal(err)
	}
	for _, val := range f {
		if !val.IsDir() {
			continue
		}
		folder := File{Name: val.Name(), Path: path + "\\" + val.Name(), IsDir: true}
		s := strings.Split(folder.Path, "/")
		folder.Path = strings.Join(s, "\\")
		folders = append(folders, folder)
	}
	return folders
}

// GetFiles 获取指定目录下的所有文件
func GetFiles(path string) []File {
	files := make([]File, 0)
	path = DealPath(path)
	f, err := ioutil.ReadDir(path)
	if err != nil {
		log.Fatal(err)
	}
	for _, val := range f {
		if val.IsDir() {
			continue
		}
		file := File{Name: val.Name(), Path: path + "\\" + val.Name()}
		s := strings.Split(file.Path, "/")
		file.Path = strings.Join(s, "\\")
		files = append(files, file)
	}
	return files
}

// GetAllThing 获取指定目录下的所有文件
func GetAllThing(path string) []File {
	files := make([]File, 0)
	path = DealPath(path)
	f, err := ioutil.ReadDir(path)
	if err != nil {
		log.Fatal(err)
	}
	for _, val := range f {
		file := File{Name: val.Name(), Path: path + "\\" + val.Name()}
		if val.IsDir() {
			file.IsDir = true
		}
		s := strings.Split(file.Path, "/")
		file.Path = strings.Join(s, "\\")
		files = append(files, file)
	}
	sort.Sort(FileSlice(files))
	return files
}

// PathExists 判断是否存在对应路径的文件
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func GetUpdateTime(path string) (int64, error) {
	info, err := os.Stat(path)
	if err != nil {
		return 0, err
	}
	return info.ModTime().Unix(), nil
}

// AddFolderFromPath 创建文件夹
func AddFolderFromPath(path string) error {
	path = DealPath(path)
	exist, err := PathExists(path)
	if err != nil {
		return err
	}
	if exist {
		return errors.New("folder exists！")
	}
	err = os.Mkdir(path, os.ModePerm)
	if err != nil {
		return err
	}
	return nil
}

func DeleteFile(path string) error {
	path = DealPath(path)
	err := os.RemoveAll(path)
	return err
}
